package xdTool

import groovy.sql.Sql
import org.hibernate.Hibernate
import sysUtil.BeetlUtil
import sysUtil.SysCommUtil

import java.sql.Clob

class XdTableColCfg {

    String field;
    String title;
    String width;
    String  minWidth= "60";
    String type ="normal"; //numbers（序号列）/space（空列）/radio（单选框列，layui 2.4.0 新增）/normal（常规列，无需设定）
    String fixed ;//固定列(left /right)
    String hide="false" ; // 是否初始隐藏列
    String totalRow = "false"; //是否开启合计列
    String totalRowText ;//合计列自定义现实文本
    String sort = "false";//是否允许排序
    String align = "center";//单元格排列方式
    String style ;
    Clob colspan = SysCommUtil.String2Clob("1");
    String rowspan ="1";
    Clob templet;
    Long xdTableId;

    String mergeFlag = "false"//是合并单元格
    String mergeRefField
    int grade=1 //第几级表头
    int colIndex=0 //列排序

    String dataType = "String"//数据类型
    String primaryKey   //主键
    String primaryValue // 主键值
    String combKey = "false" //逻辑主键

    Long paramId //绑定字段值来源：select值

    String creator ;//操作人
    String updater;//最近一次更新人
    Date dateCreated;
    Date lastUpdated;

    static constraints = {
        field(nullable: true)
        title(nullable: true)
        width(nullable: true)
        minWidth(null:true)
        type(nullable: true)
        fixed(nullable: true)
        totalRow(nullable: true)
        totalRowText(nullable: true)
        sort(nullable: true)
        align(nullable: true)
        style(nullable: true)
        mergeFlag(nullable: true)
        mergeRefField(nullable: true)

        primaryValue(nullable: true)
        primaryKey(nullable: true)

        hide(nullable: true)
        colspan(nullable: true)
        rowspan(nullable: true)
        templet(nullable: true)
        paramId(nullable: true)

        grade(nullable: false)
        colIndex(nullable: false)
        xdTableId(nullable: false)
        creator(nullable: false)
        updater(nullable: true)
    }

    static mapping = {
        version false
    }

    def sysDBUtilService
    def toLayUiColsModel(Map params){
        def colspanNew = SysCommUtil.Clob2String(this.colspan)
        if(!SysCommUtil.isDigit(colspanNew)){
            XdTableCfg xdTableCfg = XdTableCfg.get(this.xdTableId)
            XdWidgetPanel xdWidgetPanel = XdWidgetPanel.get(xdTableCfg.widgetPanelId)
            def db = sysDBUtilService.getGroovySqlInstanceById(xdWidgetPanel.dataSourceId)
            def sql = BeetlUtil.getStrTemplate(params,String.valueOf("select * from (${colspanNew}) colspan"))
            colspanNew = db?.rows(sql)?.first()?.getAt(0)?:1
        }
        colspanNew = Integer.parseInt(String.valueOf(colspanNew))

        def mergeField = new HashMap()
        if( Boolean.parseBoolean(mergeFlag) && this.field  ){
            //key:待合并列,value:参照合并列
            mergeField.put(this.field,this.mergeRefField)
        }

        return [id:this.id,field:field,title:title?:field,width:width,type:type,fixed:fixed,hide:Boolean.parseBoolean(hide),
                totalRow:Boolean.parseBoolean(totalRow),totalRowText:totalRowText,
                sort:Boolean.parseBoolean(sort),align:align,style:style,
                colspan:colspanNew,rowspan:Integer.parseInt(rowspan?:"1"),minWidth:this.minWidth,
                templet:SysCommUtil.Clob2String(templet),xdTableId:xdTableId,mergeFlag:Boolean.parseBoolean(mergeFlag),
                grade:grade,colIndex:colIndex,mergeRefField:mergeRefField,mergeField:mergeField,
                dataType:dataType?:"String",primaryKey:primaryKey,primaryValue:primaryValue,combKey:combKey]
    }

    /**
     * 将页面传参格式化为字段配置属性
     * @param xdTableId
     * @param params
     * @return
     */
    static formatParamsToColType(xdTableId,Map params){
        def fields  = XdTableColCfg.findAllByXdTableIdAndFieldIsNotNull(Long.parseLong(String.valueOf(xdTableId)))
        fields.each {
            def field = it.field
            def dataType = it.dataType
            def keyFlag = it.primaryKey?true:Boolean.parseBoolean(it.combKey)

            if(params.containsKey(field)){
                switch (dataType){
                    case "String":
                        break;
                    case "Number":
                        params."${field}" = SysCommUtil.isDigit(params."${field}")?params."${field}":null
                        if(keyFlag){
                            params."_${field}" = SysCommUtil.isDigit(params."${field}")?params."${field}":null
                        }
                        break;
                    case  "Date":
                        def date = SysCommUtil.parseString2Date(params."${field}")
                        params."${field}" = date?new java.sql.Timestamp(date.getTime()):null
                        if(keyFlag){
                            params."_${field}" = date?new java.sql.Timestamp(date.getTime()):null
                        }
                        break;
                }
            }
        }
    }
}
